import pymysql

from common.db_helper import DBHelper


class DbTools(object):
    @classmethod
    def __get_conn(cls):
        # tpshop商城的数据路连接
        return pymysql.connect(host="192.168.20.139",
                               port=3306, user='tpshop_root',
                               passwd='123456', db='tpshop',
                               charset='utf8')

    @classmethod
    def query_goods_name_by_goods_id(cls,sql):
        # 创建链接
        conn = DbTools.__get_conn()
        try:  # 通过with可以自动关闭游标
            with conn.cursor() as cursor:
                # 执行sql
                cursor.execute(sql)
                print("影响的行数",conn.affected_rows())
                res = cursor.fetchone()
            return res
        except Exception as e:
            print("查询失败",e)
        finally:
            cursor.close()
            conn.close()
    @classmethod
    def insert_goods(cls,sql):
        conn = DbTools.__get_conn()
        try:
            with conn.cursor() as cursor:
                cursor.execute(sql)
                conn.commit()
                print("影响的行数", conn.affected_rows())
        except Exception as e:
            conn.rollback()
            print("回滚事务",e)
        finally:
            cursor.close()
            conn.close()



if __name__ == '__main__':

    my_sql = 'select goods_name from tp_goods where goods_id=5;'

    result = DbTools.query_goods_name_by_goods_id(my_sql)
    print(result)

